<?php defined('SYSPATH') or die('No direct script access.');
/**
 * 文章管理
 *
 * @author  Yellow.Chow <aultoale@gmail.com>
 * @version $Id: article.php 1 2014-01-13 15:05:51Z zhouyl $
 * @license http://www.gnu.org/licenses/gpl-3.0.html    GPL 3
 */
class Controller_Admin_Article extends Controller_Admin_Base
{

    /**
     * 文章列表
     */
    public function action_index()
    {
        $this->privilege('article.list');

        $this->view->cat_id  = (int) $this->request->query('cat_id');
        $this->view->keyword = trim($this->request->query('keyword'));

        $autosort = $this->autosort('art.article_id', 'desc');

        $sql = Model::factory('article')->all_sql()
            ->order_by($autosort->field, $autosort->direct);

        if ($this->view->keyword)
        {
            $sql->where('art.title', 'LIKE', '%'.$this->view->keyword.'%');
        }

        if ($this->view->cat_id)
        {
            $cat = Model::factory('article_category')->get($this->view->cat_id);
            $sql->where('cat.path', 'LIKE', $cat['path'].'%');
        }

        $this->view->pagination = new Pager($sql);
    }

    /**
     * 添加新文章
     */
    public function action_add()
    {
        $this->privilege('article.add');

        $model = Model::factory('article');

        if ($this->request->is_post())
        {
            if ( ! $model->add($this->request->post()))
            {
                $this->view->errors = $model->errors('admin.article');
            }
            $this->render('admin/common/message');
        }
    }

    /**
     * 编辑文章
     */
    public function action_edit()
    {
        $this->privilege('article.edit');

        $article_id = $this->request->param('id');
        $model = Model::factory('article');
        $article = $model->get($article_id);

        if ( ! $article)
        {
            $this->message('admin.article.not_found')
                ->link(URL::site('admin/article'), 'admin.article.index_url')
                ->render();
        }

        if ($this->request->is_post())
        {
            if ( ! $model->edit($article_id, $this->request->post()))
            {
                $this->view->errors = $model->errors('admin.article');
            }
            $this->render('admin/common/message');
        }

        $this->view->set($article);
    }

    /**
     * 删除文章
     */
    public function action_del()
    {
        $this->privilege('article.del');

        $article_id = $this->request->param('id');
        $model = Model::factory('article');

        if ( ! $model->del($article_id))
        {
            $this->view->errors = $model->errors('admin.article');
        }

        $this->render('admin/common/message');
    }

}